/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.doeacc.tms.web.jsf;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJBAccessException;
import javax.faces.FacesException;
import javax.faces.application.NavigationHandler;
import javax.faces.context.ExceptionHandler;
import javax.faces.context.ExceptionHandlerWrapper;
import javax.faces.context.FacesContext;
import javax.faces.event.ExceptionQueuedEvent;
import javax.faces.event.ExceptionQueuedEventContext;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author slok
 */
public class AccessDeniedExceptionHandler extends ExceptionHandlerWrapper {

    private ExceptionHandler wrapped;

    public AccessDeniedExceptionHandler(ExceptionHandler wrapped) {
        this.wrapped = wrapped;
    }

    @Override
    public ExceptionHandler getWrapped() {
        return this.wrapped;
    }

    @Override
    public void handle() throws FacesException {

        for (Iterator<ExceptionQueuedEvent> i = getUnhandledExceptionQueuedEvents().iterator(); i.hasNext();) {

            ExceptionQueuedEvent event = i.next();

            ExceptionQueuedEventContext context = (ExceptionQueuedEventContext) event.getSource();

            Throwable t = context.getException();

            if (t instanceof EJBAccessException || t.getCause() instanceof EJBAccessException) {

                FacesContext fc = FacesContext.getCurrentInstance();
                NavigationHandler nav = fc.getApplication().getNavigationHandler();

                try {
                    try {
                        ((HttpServletResponse) fc.getExternalContext().getResponse()).sendRedirect("/tms/home");
                    } catch (IOException ex) {
                        Logger.getLogger(AccessDeniedExceptionHandler.class.getName()).log(Level.SEVERE, null, ex);
                    }

                } finally {
                    i.remove();

                }

            }

        }
        getWrapped().handle();
    }
}
